/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logic.business;

import data.EntityContainer;
import data.model.Route;
import data.xml_persistence.logic.XMLTransformer;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 *
 * @author Zenit
 */
public class FileManipulator {

    private EntityContainer entityContainer;
    private String fileName;
    private DataEditor dataEditor;

    private FileManipulator() {
    }

    public static FileManipulator getInstance() {
        return FileManipulatorHolder.INSTANCE;
    }

    private static class FileManipulatorHolder {

        private static final FileManipulator INSTANCE = new FileManipulator();
    }

    public void saveFile() {
        XMLTransformer.marshal(entityContainer, fileName);
    }

    public void saveFile(String fileName) {
        XMLTransformer.marshal(entityContainer, fileName);
    }

    public DataEditor readFile(String fileName) throws IOException {
        this.fileName = fileName;
        entityContainer = XMLTransformer.unmarshal(fileName);
        this.dataEditor = new DataEditor(entityContainer);
        return dataEditor;
    }

    public DataEditor startNewProject(String fileName) {
        this.entityContainer = new EntityContainer();
        this.dataEditor = new DataEditor(entityContainer);
        this.fileName=fileName;
        return new DataEditor(entityContainer);
    }

    public void exportToCSV(String fileName) {
        try {
            // Create file 
            FileWriter fstream = new FileWriter(fileName);
            BufferedWriter out = new BufferedWriter(fstream);

            String result = createCSV();

            out.write(result);
            //Close the output stream
            out.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }

    private String createCSV() {
        StringBuilder builder = new StringBuilder();
        List<Route> routes = dataEditor.getOptimizedRoutes();
        builder.append("id;departure airport name; arrival airport name; route rating; passengers per week;").append(System.getProperty("line.separator"));
        for (Route route : routes) {
            builder.append(route.getId()).append(";");
            builder.append(route.getDepartureAirport().getName()).append(";");
            builder.append(route.getArrivalAirport().getName()).append(";");
            builder.append(route.getRating()).append(";");
            builder.append(route.getWeeklyPassengers()).append(";").append(System.getProperty("line.separator"));
        }
        
        return builder.toString();

    }
}
